﻿var token = getCookie("token");
$.ajaxSetup({
    global: true,
    dataType: 'json',
    timeout: 5000,
    headers: {
        'Token': token
    }
});

$(function () {
    var sysUid = $.cookie('sysuid');
    if (!sysUid) {
        //登录判断如果cookie 中没有sysuid 没就跳转登录
        parent.top.window.location.replace('login.html');
    }
});

var url = 'http://mybok.skydige.com/';
var myreg = /^1[34578]\d{9}$/;
/*
 -----------------------------------------------------------------------------------
 index 方法
 */
//获取用户信息（通过用户id）
function userInfo(uid) {
    $.ajax({
        url: url + 'member/' + uid,                             //请求地址
        type: 'GET',                                                   //请求类型
        dataType: "json",                                               //返回值类型
        //  data: { "phone": keywords },                                 //参数
        success: function (data) {
            if (data.code == 200 && data.data != null && data.data != "") {
                var phone = data.data.phone;            //电话
                var real_name = data.data.real_name;    //姓名
                var money = data.data.money;            //金额
                var number = data.data.number;          //卡号
                var integral = data.data.integral;      //积分
                var userid = data.data.uid;
                parent.$('#real_name').text('姓名：' + real_name);
                parent.$('#phone').text('电话：' + phone);
                parent.$('#money').text('余额：' + money);
                parent.$('#number').text('卡号：' + number);
                parent.$('#integral').text('积分：' + integral);
                parent.$('#userid').text(userid);

                $.cookie('uid', data.data.uid);
                $.cookie('phone', data.data.phone);
                $.cookie('money', data.data.money);
                $.cookie('number', data.data.number);
            }
            else {
                message('message.html?t=512', '300px', '200px');
            }
        }
    })
}

//首页输入数据 查询数据
function CommodityDetails(keywords) {
    if (keywords.length == 11) {
        $.ajax({
            url: url + 'member/phone',                             //请求地址
            type: 'POST',                                                   //请求类型
            dataType: "json",                                               //返回值类型
            data: {"phone": keywords},                                 //参数
            success: function (data) {
                if (data.code == 200 && data.data != null && data.data != "") {
                    var phone = data.data.phone;            //电话
                    var real_name = data.data.real_name;    //姓名
                    var money = data.data.money;            //金额
                    var number = data.data.number;          //卡号
                    var integral = data.data.integral;      //积分
                    var userid = data.data.uid;
                    $('#real_name').text('姓名：' + real_name);
                    $('#phone').text('电话：' + phone);
                    $('#money').text('余额：' + money);
                    $('#number').text('卡号：' + number);
                    $('#integral').text('积分：' + integral);
                    $('#userid').text(userid);

                    $.cookie('uid', data.data.uid);
                    $.cookie('phone', data.data.phone);
                    $.cookie('money', data.data.money);
                    $.cookie('number', data.data.number);
                }
                else {
                    message('message.html?t=501', '300px', '200px');
                }
            }
        })
    }
    else {
        $.ajax({
            url: url + 'goods/detail',                                //请求地址
            type: 'POST',                                      //请求类型
            dataType: "json",                                  //返回值类型
            data: {"keywords": keywords},                     //参数
            success: function (data) {
                if (data.code == 200 && data.data != null) {
                    var article_no = data.data.bar_code;  //货号
                    var zh_name = data.data.zh_name;        //品名
                    var price = parseFloat(data.data.price);            //价格
                    var tax = parseFloat(0);                //税额
                    var subtotal = price + tax;             //小计
                    var goods_id = data.data.goods_id;
                    var taocang_id=data.data.taocang_id;

                    Shoppingcartadd(goods_id);


                    // 去除所有选择项
                    $('#ice tr').attr("id", "");
                    var tableId = document.getElementById("ice");
                    var xarticle_no = "", xzh_name = "", xsl = "", xprice = "", xtax = "", xsubtotal = "";
                    var repeat = 0;
                    for (var i = 0; i < tableId.rows.length; i++) {
                        var xgoods_id = tableId.rows[i].cells[7].innerHTML;
                        if (xgoods_id == goods_id) {
                            xarticle_no = tableId.rows[i].cells[1].innerHTML;    //原数据货号
                            xzh_name = tableId.rows[i].cells[2].innerHTML;       //原数据品名
                            xsl = tableId.rows[i].cells[3].innerHTML;            //原数据sl
                            xprice = tableId.rows[i].cells[4].innerHTML;         //原数据价格
                            xtax = tableId.rows[i].cells[5].innerHTML;           //原数据税额
                            xsubtotal = tableId.rows[i].cells[6].innerHTML;      //原数据小计
                            repeat = 1;
                            var tr = tableId.rows[i];
                            tr.parentNode.removeChild(tr);
                            break;
                        }
                    }
                    if (repeat == 1) {
                        xsl = parseInt(xsl) + parseInt('1');                               //新数量
                        var total = xsl * parseFloat(price);                       //总价
                        xtax = parseInt(xtax) + parseFloat(tax);
                        total = total + xtax;

                        // 新数据默认选中
                        $("#ice").prepend('<tr id="list_xz"><td width=\"100\">1</td><td width="160">' + article_no + '</td><td width="400"><div>' + zh_name + '</div></td><td width="100">' + xsl + '</td><td width="100">￥' + price + '</td><td width="100" style="display:none">' + tax + '</td><td width="100">￥' + total + '</td><td style="display:none">' + goods_id + '</td> </tr>');
                    }
                    else {
                        // 新数据默认选中
                        $("#ice").prepend('<tr id="list_xz"><td width=\"100\">1</td><td width="160">' + article_no + '</td><td width="400"><div>' + zh_name + '</div></td><td width="100">1</td><td width="100">￥' + price + '</td><td width="100" style="display:none">' + tax + '</td><td width="100">￥' + subtotal + '</td><td style="display:none">' + goods_id + '</td> </tr>');
                    }

                    //  更改序列
                    var totalquantity = parseInt(0);
                    var total = parseFloat(0); //应收金额

                    for (var i = 0; i < tableId.rows.length; i++) {
                        var xl = i + 1;
                        tableId.rows[i].cells[0].innerHTML = xl;
                        var linegauge = tableId.rows[i].cells[6].innerHTML;
                        var quantity = parseInt(tableId.rows[i].cells[3].innerHTML);
                        if (linegauge != "") {
                            linegauge = parseFloat(linegauge.substring(1, linegauge.length));
                            total = total + linegauge;
                            totalquantity = totalquantity + quantity;
                        }
                    }

                    // 得到折让
                    var discount = parseFloat($('#zr').text());
                    total = total - discount;
                    $('.bill_money_d').text(numFloat(total));
                    $('#sl').text(totalquantity);//这里返回的是：1；

                }
                else {
                    message('message.html?t=505', '300px', '200px');
                }
            }
        })
    }
}
//获取套餐
function taocang(id) {
    var zr=0;
    $.ajax({
        url: url + 'taocang/findzr/' + id,                                //请求地址
        type: 'GET',                                      //请求类型
        dataType: "json",                                  //返回值类型
        data: {},                     //参数
        success: function (data) {
            if (data.code == 200 && data.data.zr > 0) {
                zr=data.data.zr;
                parent.parent.$('#zr').text(data.data.zr);
            }else{
                zr=data.data.zr;
                parent.parent.$('#zr').text(0);
            }
        }
    });
    return zr;
}

function up_zr(keywords) {
    $.ajax({
        url: url + 'goods/detail',                                //请求地址
        type: 'POST',                                      //请求类型
        dataType: "json",                                  //返回值类型
        data: {"keywords": keywords},                     //参数
        success: function (data) {
            if (data.code == 200 && data.data != null) {
                var article_no = data.data.bar_code;  //货号
                var zh_name = data.data.zh_name;        //品名
                var price = parseFloat(data.data.price);            //价格
                var tax = parseFloat(0);                //税额
                var subtotal = price + tax;             //小计
                var goods_id = data.data.goods_id;
                var taocang_id=data.data.taocang_id;

                if (taocang_id > 0){
                    taocang(taocang_id);
                }
            }
            else {
                message('message.html?t=505', '300px', '200px');
            }
        }
    })
}
//更新商品数量
function Updatequantity(id, number) {
    $.ajax({
        url: url + 'shopping/cart/' + id,                                //请求地址
        type: 'POST',                                      //请求类型
        dataType: "json",                                  //返回值类型
        data: {"counts": number},                     //参数
        success: function (data) {
            if (data.code == 200 && data.data > 0) {

                //up_zr(id);
                var mNum = QuantityValue();
                var commodityAmount = $('#list_xz td').eq(4).text(); //金额（单商品金额总计）
                //提取金额（单价）
                commodityAmount = parseFloat(commodityAmount.substring(1, commodityAmount.length));

                //单个商品的总价
                var lumpSum = commodityAmount * number;
                //税费
                var taxrate = parseFloat($('#list_xz td').eq(5).text());
                taxrate = taxrate * number;
                //小计
                var subtotal = lumpSum - taxrate;
                $('#list_xz td').eq(3).text(number);
                //$('#list_xz td').eq(4).text('￥' + numFloat(lumpSum));
                $('#list_xz td').eq(6).text('￥' + numFloat(subtotal));

                var totalquantity = parseInt(0);
                var total = parseFloat(0); //应收金额
                var tableId = document.getElementById("ice");
                for (var i = 0; i < tableId.rows.length; i++) {
                    var linegauge = tableId.rows[i].cells[6].innerHTML;
                    var quantity = parseInt(tableId.rows[i].cells[3].innerHTML);
                    if (linegauge != "") {
                        linegauge = parseFloat(linegauge.substring(1, linegauge.length));
                        total = total + linegauge;
                        totalquantity = totalquantity + quantity;
                    }
                }
                //得到折让
                var discount = parseFloat($('#zr').text());
                total = total - discount;
                $('.bill_money_d').text(numFloat(total));
                $('#sl').text(totalquantity);
            }
            else {
                message('message.html?t=503', '300px', '200px');
            }
        }
    })
}

//删除商品数量
function Deletemerchandise(id) {
    // var commodityID = "[" + id + "]";
    $.ajax({
        url: url + 'shopping/delete',                                //请求地址
        type: 'POST',                                      //请求类型
        dataType: "json",                                  //返回值类型
        data: {"ids": id},                      //参数
        success: function (data) {
            if (data.code == 200 && data.data != 0) {
                var current = $('#list_xz').index('tr');
                //从新计算数量
                var sl = parseInt($('#sl').text());
                var quantityorder = parseInt($('#list_xz td').eq(3).text());
                sl = sl - quantityorder;
                $('#sl').text(sl);
                //从新计算金额
                var commodityAmount = $('#list_xz td').eq(6).text(); //金额（单商品金额总计）
                //提取金额
                commodityAmount = parseFloat(commodityAmount.substring(1, commodityAmount.length));
                var total = parseFloat($('.bill_money_d').text()) - commodityAmount;

                $('.bill_money_d').text(numFloat(total));

                $('#list_xz').remove();
                if (current == $('#ice tr').length) {
                    index = current - 1;
                }
                if ($('#ice tr').length > 0) {
                    selectRow();
                }

                //更改序列
                var tableId = document.getElementById("ice");
                for (var i = 0; i < tableId.rows.length; i++) {
                    var xl = i + 1;
                    tableId.rows[i].cells[0].innerHTML = xl;
                }
            }
            else {
                message('message.html?t=504', '300px', '200px');
            }
        }
    })
}

//清空购物车
function DeletemerchandiseList(id) {
    $.ajax({
        url: url + 'shopping/clear',                                //请求地址
        type: 'POST',                                      //请求类型
        dataType: "json",                                  //返回值类型
        //     data: { "ids": id },                      //参数
        success: function (data) {
            if (data.code == 200) {
                parent.parent.$('#zr').text(0);
                parent.parent.$('.bill_money_d').text(0.00);
                parent.parent.$('#sl').text(0);
                var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                parent.parent.$('#ice').find('tr').remove();
                parent.layer.close(index);
            }
            else {
                message('message.html?t=504', '300px', '200px');
            }
        }
    })
}

//添加购物车
function Shoppingcartadd(goods_id) {
    var userid = $.cookie('uid');
    if (userid == null || userid == "") {
        userid = 0;
    }
    $.ajax({
        url: url + 'shopping/cart',                        //请求地址
        type: 'POST',                                      //请求类型
        dataType: "json",                                  //返回值类型
        data: {"member_id": userid, "goods_id": goods_id},                        //参数
        success: function (data) {
            if (data.code == 200 && data.data > 0) {

            }
            else {
                alert("Code:" + data.code + " Msg:" + data.message);
            }
        }
    })
}

/*
 -----------------------------------------------------------------------------------
 挂单数据
 */
//挂单列表及总数
function guadanlist(type) {
    $.ajax({
        url: url + 'shopping/pending',                //请求地址
        type: 'GET',                                      //请求类型
        dataType: "json",                                  //返回值类型
        success: function (data) {
            if (data.code == 200 && data.data != null && data.data != "") {
                if (type == 1) {
                    parent.parent.$('#oddnumber').html("挂单数：" + data.data.total);
                }
                else {
                    var json = eval(data.data);
                    for (var i = 0; i < data.data.total; i++) {
                        var style = "";
                        if (data.data.total - 1 == i) {
                            style = 'class="a"';
                        }
                        $("#ice").prepend('<tr ' + style + '><td style="display:none">' + json[i].pending_no + '</td><td style="display:none">' + json[i].created_at + '</td><td>' + json[i].pending_no + '</td></tr>');
                    }
                }
            }
            else {
                message('message.html?t=506', '300px', '200px');
            }
        }
    })
}

//获取挂单
function getGuadan(pending_no) {
    $.ajax({
        url: url + 'shopping/get',                     //请求地址
        type: 'POST',                                      //请求类型
        dataType: "json",                                  //返回值类型
        data: {"pendingNo": pending_no},                      //参数
        success: function (data) {
            if (data.code == 200 && data.data != "0") {
                getcart();
                guadanlist(1);
            }
            else {
                message('message.html?t=506', '300px', '200px');
            }
        }
    })
}

//删除挂单
function delGuadan(pending_no) {
    $.ajax({
        url: url + 'shopping/cancel',                     //请求地址
        type: 'POST',                                      //请求类型
        dataType: "json",                                  //返回值类型
        data: {"pendingNo": pending_no},                      //参数
        success: function (data) {
            if (data.code == 200 && data.data == "1") {
                guadanlist(1);
                $('.a').remove();
                var current = $('.a').index('tr');
                if (current == $('#ice tr').length) {
                    index = current - 1;
                }
                if ($('#ice tr').length > 0) {
                    $('#ice tr').attr("class", "");
                    $('#ice tr').eq(index).attr("class", "a");
                }
                else {
                    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                    parent.$('#sku').focus();
                    parent.layer.close(index);
                }
            }
            else {
                message('message.html?t=507', '300px', '200px');
            }
        }
    })
}

//获取购物车
function getcart() {
    var jsurl = "";
    var uid = $.cookie('uid');
    if (uid != null || uid != "" || uid != "0") {
        jsurl = '?memberId=' + uid;
    }

    $.ajax({
        url: url + 'shopping/cart' + jsurl,                     //请求地址
        type: 'GET',                                      //请求类型
        dataType: "json",                                  //返回值类型
        success: function (data) {
            if (data.code == 200 && data.data.length > 0) {
                var userid = "";
                parent.parent.$('#ice').find('tr').remove();
                var json = eval(data.data);
                for (var i = 0; i < json.length; i++) {
                    userid = json[i].uid;
                    var style = "";
                    if (json.length - 1 == i) {
                        style = 'id="list_xz"';
                    }
                    var article_no = json[i].article_no;               //货号
                    var zh_name = json[i].zh_name;                    //品名
                    var price = parseFloat(json[i].price);            //价格
                    var sl = parseInt(json[i].counts);            //数量
                    var tax = parseFloat(0);                            //税额
                    var subtotal = price * sl + tax;                         //小计
                    var goods_id = json[i].goods_id;                  //id

                    up_zr(article_no);

                    parent.$("#ice").prepend('<tr ' + style + '><td width=\"100\">' + i + '</td><td width="160">' + article_no + '</td><td width="400"><div>' + zh_name + '</div></td><td width="100">' + sl + '</td><td width="100">￥' + price + '</td><td width="100" style="display:none">' + tax + '</td><td width="100">￥' + subtotal + '</td><td style="display:none">' + goods_id + '</td> </tr>');
                }
                if (userid > 0) {
                    userInfo(userid);
                }
                //  更改序列
                var totalquantity = parseInt(0);
                var total = parseFloat(0); //应收金额
                var tableId = parent.document.getElementById("ice");
                for (var i = 0; i < tableId.rows.length; i++) {
                    var xl = i + 1;
                    tableId.rows[i].cells[0].innerHTML = xl;
                    var linegauge = tableId.rows[i].cells[6].innerHTML;
                    var quantity = parseInt(tableId.rows[i].cells[3].innerHTML);
                    if (linegauge != "") {
                        linegauge = parseFloat(linegauge.substring(1, linegauge.length));
                        total = total + linegauge;
                        totalquantity = totalquantity + quantity;
                    }
                }
                // 得到折让
                var discount = parseFloat(parent.$('#zr').text());
                total = total - discount;
                parent.$('.bill_money_d').text(numFloat(total));
                parent.$('#sl').text(totalquantity);

                guadanlist(1);
                var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                parent.layer.close(index);
            }
            else if (data.code != 200) {
                message('message.html?t=508', '300px', '200px');
            }
        }
    })
}

//新挂单
function addGuadan() {
    $.ajax({
        url: url + 'shopping/created',               //请求地址
        type: 'POST',                                      //请求类型
        dataType: "json",                                  //返回值类型
        success: function (data) {
            if (data.code == 200 && data.data != "0") {
                parent.parent.$('#ice').find('tr').remove();
                parseFloat(parent.$('#zr').text(0));
                parent.$('.bill_money_d').text(0.00);
                parent.$('#sl').text(0);
                guadanlist(1);

                parent.$('#real_name').text('姓名：');
                parent.$('#phone').text('电话：');
                parent.$('#money').text('余额：');
                parent.$('#number').text('卡号：');
                parent.$('#integral').text('积分：');
                parent.$('#userid').text();

                $.cookie('uid', null);
                $.cookie('phone', null);
                $.cookie('money', null);
                $.cookie('number', null);
            }
            else {
                message('message.html?t=509', '300px', '200px');
            }
        }
    });
}

/*
 -----------------------------------------------------------------------------------
 用户充值和新用户
 */
//充值方法 参数：充值金额、门店id、备注
function recharge(number, money, store_id, memo) {
    if (money == "" || number == "") {
        message('message.html?t=201', '300px', '200px');
    }
    else {
        $.ajax({
            url: url + 'member/recharge/created',                             //请求地址
            type: 'POST',                                                   //请求类型
            dataType: "json",                                               //返回值类型
            data: {
                "uid": number, "store_id": store_id,
                "money": money, "type": 1, "memo": memo, "status": 1   //参数
            },
            success: function (data) {
                if (data.code == 200 && data.data > 0) {
                    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                    parent.layer.close(index);
                    var money_y = parent.parent.$('#money').html()
                    money_y = money_y.substring(3, money_y.length);
                    var money_s = parseFloat(money) + parseFloat(money_y);
                    parent.parent.$('#money').html("余额：" + money_s);
                    parent.$('#sku').focus();
                    ticket(0, 3, money);
                }
                else {
                    message('message.html?t=511', '300px', '200px');
                }
            }
        })
    }
}

//新用户 参数：电话号码、卡号、真实姓名、备注
function newmember(phone, number, real_name, memo) {
    if (phone == "" || number == "" || real_name == "") {
        message('message.html?t=202', '300px', '200px');
    }
    else {
        if (!myreg.test(phone)) {
            message('message.html?t=102', '300px', '200px');
        }
        else {
            $.ajax({
                url: url + 'member',                                        //请求地址
                type: 'POST',                                                   //请求类型
                dataType: "json",                                               //返回值类型
                data: {
                    "phone": phone, "number": number,
                    "real_name": real_name, "memo": memo, "status": 1, "token": token   //参数
                },
                success: function (data) {
                    if (data.code == 200 && data.data != "1") {
                        var index = parent.top.layer.getFrameIndex(window.name); //获取窗口索引
                        parent.top.layer.close(index);
                        parent.$('#sku').focus();
                    }
                    else {
                        alert("Code:" + data.code + " Msg:" + data.message);
                    }
                }
            })
        }
    }
}

/**
 * 第三方支付
 */
function payments(money, cardMoney, code, payType, isRefund) {
    var uid = $.cookie('uid');
    $.post(url + 'payments', {
        totalAmount: money,
        authCode: code,
        payType: payType
    }, function (data) {
        if (data.message === 'Success') {
            if (isRefund == 1) {
                var tradeNo = $.cookie('tradeNo'),
                    goodsIds = $.cookie('tttid'),
                    counts = $.cookie('tttsl');
                paymentMethodt(tradeNo, goodsIds, counts, money);
            }
            paymentMethod(uid, code, cardMoney, money, payType, 0, data.data.outTradeNo, data.data.tradeNo);
        } else {
            message('message.html?t=516', '300px', '200px');
        }
    });
}

/*
 -----------------------------------------------------------------------------------
 支付
 */
//支付： 用户id、商户授权码、卡片金额、金额、支付方式
function paymentMethod(uid, authCode, cardAmount, amount, payType, totalAmount, outTradeNo, tradeNo) {
    if (parseFloat(totalAmount).toFixed(2) == parseFloat(amount).toFixed(2)) {
        cardAmount = 0;
    }
    $.ajax({
        url: url + 'shopping',                                        //请求地址
        type: 'POST',                                                   //请求类型
        dataType: "json",                                               //返回值类型
        data: {
            "uid": uid, "authCode": authCode,
            "outTradeNo": outTradeNo, "tradeNo": tradeNo,
            "cardAmount": cardAmount, "amount": amount, "payType": payType   //参数
        },
        success: function (data) {
            if (data.code == 200 && data.data > 0) {
                parent.$("#userid").html();
                parent.$("#real_name").html();
                parent.$("#number").html();
                parent.$("#phone").html();
                parent.$("#integral").html();
                parent.$("#money").html();
                $.cookie('uid', null);
                $.cookie('phone', null);
                $.cookie('money', null);
                $.cookie('number', null);
                ticket(data.data, 1, 0);
            }
            else {
                message('message.html?t=510', '300px', '200px');
            }
        }
    })
}

function ticket(outTradeNo, ticketType, rechargeMoney) {
    var routes = 'shopping/ticket';
    if (ticketType == 3) {
        routes = 'member/ticket/detail';
    }
    $.ajax({
        url: url + routes,
        type: 'POST',
        dataType: "json",
        data: {
            "outTradeNo": outTradeNo,
            "uid": $.cookie('uid'),
            "ticketType": ticketType,
        },
        success: function (data) {
            if (data.code == 200 && data.data != 0) {
                var index = parent.layer.getFrameIndex(window.name);
                myAddHtml(printerStr(data.data, ticketType, rechargeMoney));
                parent.layer.close(index);
                parent.top.window.location.reload();
            }
        }
    });
}

function printerStr(data, ticketType, rechargeMoney) {
    var strHtml = '',
        strCardHtml = '',
        str = data.out_trade_no;
    if (ticketType == 1) {
        var options = {
            format: "CODE128",
            displayValue: false,
            fontSize: 24,
            height: 60
        };
        $('#barcode').JsBarcode(str, options);
    }
    strHtml += "<div style=\'text-align: center;\'><img src=\'http://www.collect.loc/img/ticket_logo.png\' width=\'70%\'></div>";
    strHtml += "    <div style=\'font-size: 12px; text-align: center; margin-top: 5px;\'>重庆象米国际欧洲生活品质超市<br>【" + data.storeConfig.storeName + "】</div>";
    strHtml += "    <div style=\'text-align: left; font-size: 10px; margin-top: 8px\'>地址：" + data.storeConfig.address + "<br>电话：" + data.storeConfig.tel + "<br>时间：" + data.created_at + "</div>";
    strHtml += "    <div style=\'border-top:#000 1px dotted; padding-top:5px; border-bottom:#000 1px dotted; padding-bottom:5px; margin-top: 5px;\'>";
    if (ticketType == 3) {
        strHtml += "    <div style=\'text-align: left; font-size: 12px; margin-top: 8px;\'>卡号：" + data.number + "<br>手机号：" + data.phone + "<br>充值金额：" + rechargeMoney + "<br>余额：" + data.money + "</div>";
        strHtml += "    <table width=\'100%\' style=\'font-size: 10px;\'>";
        strHtml += "        <tr>";
        strHtml += "            <td>付款金额：</td>";
        strHtml += "            <td align=\'right\'>" + data.money + "</td>";
        strHtml += "        </tr>";
        strHtml += "    </table>";
    } else {
        strHtml += "    <table width=\'100%\' style=\'font-size: 10px; margin-top: 10px;\' border=\'0\' cellspacing=\'0\'>";
        strHtml += "        <tr style=\'margin-bottom: 5px;\'>";
        strHtml += "            <th width=\'60%\' align=\'left\'>名称</th>";
        strHtml += "            <th width=\'20%\' align=\'center\'>数量</th>";
        strHtml += "            <th width=\'20%\' align=\'right\'>价格</th>";
        strHtml += "        </tr>";
        $.each(data.detail, function (k, v) {
            strHtml += "        <tr style=\'font-size: 9px\'>";
            strHtml += "            <td>" + v.zh_name + "</td>";
            strHtml += "            <td align=\'center\'>" + v.counts + "</td>";
            strHtml += "            <td align=\'right\'>" + v.price + "</td>";
            strHtml += "        </tr>";
        });
        strHtml += "    </table>";
        strHtml += "    <div style=\'clear: both; margin-top: 5px;\'></div>";
        strHtml += "    <table width=\'100%\' style=\'font-size: 10px;\'>";
        if (data.card_amount > 0) {
            strCardHtml += "        <tr>";
            strCardHtml += "            <td>会 员 卡</td>";
            strCardHtml += "            <td align=\'right\'>" + data.card_amount + "</td>";
            strCardHtml += "        </tr>";
        }
        var srt1 = '总&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;计';
        var srt2 = '人 民 币';
        var totalAmount = (data.amount * 100 + data.card_amount * 100) / 100;
        if (data.pay_type == 2) {
            srt2 = '银 行 卡';
        } else if (data.pay_type == 4) {
            srt2 = '微信支付';
        } else if (data.pay_type == 5) {
            srt2 = '支 付 宝';
        }
        strHtml += "        <tr>";
        strHtml += "            <td>" + srt1 + "</td>";
        strHtml += "            <td align=\'right\'>" + totalAmount.toFixed(2) + "</td>";
        strHtml += "        </tr>";
        strHtml += strCardHtml;
        strHtml += "        <tr>";
        strHtml += "            <td>" + srt2 + "</td>";
        strHtml += "            <td align=\'right\'>" + data.amount + "</td>";
        strHtml += "        </tr>";
        strHtml += "    </table>";
    }
    strHtml += "    </div><div style=\'text-align: right; font-size: 12px; margin-top: 15px\'>操作人：" + $.cookie('realName') + "</div>";
    if (ticketType == 1) {
        strHtml += "    <div style=\'text-align: center; margin-top: 12px; font-size: 10px\' class=\'tm barcode2\' id=\'ywm\'></div>";
        strHtml += "    <div><img style=\'width: 100%;\' src=\'" + $('img').attr('src') + "\'/></div>";
        strHtml += "    <div style=\'font-size: 11px; text-align: center; position: relative; top: -5px;\'>" + str + "</div>";
        strHtml += "    <div style=\'text-align: center;\'><img src=\'http://www.collect.loc/img/ewm.jpg\' width=\'55%\'></div>";
    } else if (ticketType == 2) {
        strHtml += "    <div style=\'text-align: center; margin-top: 12px; font-size: 12px; line-height: 20px;\'>*****本票为退货小票*****<br />单号：" + str + "</div>";
    }
    strHtml += "    <div style=\'text-align: center;font-size: 11px;\'>谢谢惠顾，欢迎再次光临！<br>服务监督热线<br><span>400-000-9011</span></div>";
    strHtml += "    <div style=\'font-size: 11px; text-align: center\'>购物小票为退货/换货<br>开具发票等有效凭证<br>请妥善保管</div>";
    strHtml += "    <div style=\'padding-top:130px;\'>.</div>";

    return strHtml;
}

//退回支付：
function paymentMethodt(tradeNo, goodsIds, counts, amount) {
    $.ajax({
        url: url + 'shopping/refund',                                          //请求地址
        type: 'POST',                                                   //请求类型
        dataType: "json",                                               //返回值类型
        data: {
            "tradeNo": tradeNo, "goodsIds": goodsIds, "counts": counts, "amount": amount   //参数
        },
        success: function (data) {
            if (data.code == 200 && data.data != null && data.data != "") {
                parent.$("#userid").html();
                parent.$("#real_name").html();
                parent.$("#number").html();
                parent.$("#phone").html();
                parent.$("#integral").html();
                parent.$("#money").html();
                $.cookie('uid', null);
                $.cookie('phone', null);
                $.cookie('money', null);
                $.cookie('number', null);
                ticket(data.data, 2, 0);
            }
            else {
                message('message.html?t=510', '300px', '200px');
            }
        }
    })
}

/*
 -----------------------------------------------------------------------------------
 退货模式
 */
//退货列表
function returncolumn(tradeNo) {
    $.cookie('tradeNo', tradeNo);
    $.ajax({
        url: url + 'shopping/detail',                                        //请求地址
        type: 'POST',                                                   //请求类型
        dataType: "json",                                               //返回值类型
        data: {
            "tradeNo": tradeNo                                        //参数
        },
        success: function (data) {
            if (data.code == 200 && data.data.detail.length > 0) {
                var uid = data.data.uid;
                if (uid != "") {
                    userInfo(uid);
                }
                parent.parent.$('#ice').find('tr').remove();
                var json = eval(data.data.detail);
                for (var i = 0; i < json.length; i++) {
                    var style = "";
                    if (json.length - 1 == i) {
                        style = 'id="list_xz"';
                    }
                    var article_no = json[i].article_no;               //货号
                    var zh_name = json[i].zh_name;                    //品名
                    var price = json[i].price;                      //价格
                    var tax = parseFloat(0);                            //税额
                    var subtotal = price + tax;                         //小计
                    var goods_id = json[i].goods_id;                  //id
                    var counts = json[i].counts;

                    parent.$("#ice").prepend('<tr ' + style + '><td width=\"100\">' + i + '</td><td width="160">' + article_no + '</td><td width="400"><div>' + zh_name + '</div></td><td width="100">0/' + counts + '</td><td width="100">￥' + price + '</td><td width="100" style="display:none"style="display:none">' + tax + '</td><td width="100">￥0.00</td><td style="display:none">' + goods_id + '</td> </tr>');
                }
                //  更改序列
                var totalquantity = parseInt(0);
                var total = parseFloat(0); //应收金额
                var tableId = parent.document.getElementById("ice");
                for (var i = 0; i < tableId.rows.length; i++) {
                    var xl = i + 1;
                    tableId.rows[i].cells[0].innerHTML = xl;
                    var linegauge = tableId.rows[i].cells[6].innerHTML;
                    var quantity = parseInt(tableId.rows[i].cells[3].innerHTML);
                    if (linegauge != "") {
                        linegauge = parseFloat(linegauge.substring(1, linegauge.length - 1));
                        total = total + linegauge;
                        totalquantity = totalquantity + quantity;
                    }
                }
                // 得到折让
                var discount = parseFloat($('#zr').text());
                total = total - discount;
                $('.bill_money_d').text(numFloat(total));
                $('#sl').text(totalquantity);
            }
            else {
                message('message.html?t=505', '300px', '200px');
            }
        }
    })
}

/*
 -----------------------------------------------------------------------------------
 交班
 */

//交班验证
function shifttest(password) {
    var number = $.cookie('sysnumber');
    if (number == null || number == "") {
        alert("number为空！");
    }
    $.ajax({
        url: url + 'shift/check',                                        //请求地址
        type: 'POST',                                                   //请求类型
        dataType: "json",                                               //返回值类型
        data: {
            "password": password                                        //参数
        },
        success: function (data) {
            if (data.code == 200 && data.data == 1) {
                shiftTicket(number);
                shiftHandover(number);
            }
            else {
                message('message.html?t=513', '300px', '200px');
            }
        }
    });
}

function shiftTicket(number) {
    $.ajax({
        url: url + 'shift/inventory',                                        //请求地址
        type: 'POST',                                                   //请求类型
        dataType: "json",                                               //返回值类型
        data: {
            "number": number                                        //参数
        },
        success: function (data) {
            if (data.code == 200 && typeof(data.data.goodsType) != "undefined") {
                var strHtml = '',
                    weChat = typeof(data.data.payType.weChat) != "undefined" ? data.data.payType.weChat : 0,
                    bankCard = typeof(data.data.payType.bankCard) != "undefined" ? data.data.payType.bankCard : 0,
                    payPal = typeof(data.data.payType.payPal) != "undefined" ? data.data.payType.payPal : 0,
                    memberCard = typeof(data.data.payType.memberCard) != "undefined" ? data.data.payType.memberCard : 0,
                    rmb = typeof(data.data.payType.rmb) != "undefined" ? data.data.payType.rmb : 0,
                    weRefundChat = typeof(data.data.payRefundType.weChat) != "undefined" ? data.data.payRefundType.weChat : 0,
                    bankRefundCard = typeof(data.data.payRefundType.bankCard) != "undefined" ? data.data.payRefundType.bankCard : 0,
                    payRefundPal = typeof(data.data.payRefundType.payPal) != "undefined" ? data.data.payRefundType.payPal : 0,
                    memberRefundCard = typeof(data.data.payRefundType.memberCard) != "undefined" ? data.data.payRefundType.memberCard : 0,
                    rmbRefund = typeof(data.data.payRefundType.rmb) != "undefined" ? data.data.payRefundType.rmb : 0,
                    recharge = typeof(data.data.rechargeMoney) != "undefined" ? data.data.rechargeMoney : 0,
                    orderAmount = weChat + bankCard + payPal + memberCard + rmb,
                    refundAmount = data.data.totalPrice,
                    turnAmount = orderAmount - refundAmount + recharge;
                strHtml += "<div style=\'text-align: center;\'><img src=\'img/ticket_logo.png\' width=\'70%\'></div>";
                strHtml += "    <div style=\'font-size: 12px; text-align: center; margin-top: 5px;\'>重庆象米国际欧洲生活品质超市<br>【" + data.data.userInfo.storeName + "】</div>";
                strHtml += "    <div style=\'border-top:#000 1px dotted; padding-top:5px; border-bottom:#000 1px dotted; padding-bottom:5px; margin-top: 5px;\'>";
                strHtml += "        <div style=\'font-size:12px;\'>前台交班<br />单号：" + data.data.userInfo.number + "<br />收银员：" + $.cookie('realName') + "<br />开始时间：" + data.data.userInfo.startTime + "<br />结束时间：" + data.data.userInfo.endTime + "</div>";
                strHtml += "        <div style=\'border-top:#000 1px dotted; padding-top:10px;  margin-top:10px; font-size:12px;\'>销售金额：" + orderAmount.toFixed(2) + "<br />销售金额（含退货）：" + turnAmount.toFixed(2) + "<br />退款金额：" + refundAmount + "<br /></div>";
                strHtml += "        <div style=\'border-top:#000 1px dotted; padding-top:10px; border-bottom:#000 1px dotted; padding-bottom:10px; margin-top:5px; font-size:12px;\'>";
                strHtml += "            <table width=\'100%\' style=\'font-size:12px;\'>";
                strHtml += "              <tr>";
                strHtml += "                <td>应交金额：</td>";
                strHtml += "                <td align=\'right\'>" + turnAmount.toFixed(2) + "</td>";
                strHtml += "              </tr>";
                strHtml += "            </table>";
                strHtml += "        </div>";
                strHtml += "        <div style=\' border-bottom:#000 1px dotted; padding-bottom:10px; margin-top:10px;\'>";
                strHtml += "            <table width=\'100%\' style=\'font-size:12px;\'>";
                strHtml += "              <tr>";
                strHtml += "                <td>微信支付：</td>";
                strHtml += "                <td align=\'right\'>" + (weChat - weRefundChat).toFixed(2) + "</td>";
                strHtml += "              </tr>";
                strHtml += "              <tr>";
                strHtml += "                <td>支 付 宝：</td>";
                strHtml += "                <td align=\'right\'>" + (payPal - payRefundPal).toFixed(2) + "</td>";
                strHtml += "              </tr>";
                strHtml += "              <tr>";
                strHtml += "                <td>会 员 卡：</td>";
                strHtml += "                <td align=\'right\'>" + (memberCard + memberRefundCard).toFixed(2) + "</td>";
                strHtml += "              </tr>";
                strHtml += "              <tr>";
                strHtml += "                <td>银 联 卡：</td>";
                strHtml += "                <td align=\'right\'>" + (bankCard - bankRefundCard).toFixed(2) + "</td>";
                strHtml += "              </tr>";
                strHtml += "              <tr>";
                strHtml += "                <td>人 民 币：</td>";
                strHtml += "                <td align=\'right\'>" + (rmb - rmbRefund).toFixed(2) + "</td>";
                strHtml += "              </tr>";
                strHtml += "              <tr>";
                strHtml += "                <td>充    值：</td>";
                strHtml += "                <td align=\'right\'>" + recharge.toFixed(2) + "</td>";
                strHtml += "              </tr>";
                strHtml += "            </table>";
                strHtml += "        </div>";
                strHtml += "    </div><div style=\'margin-top:10px; font-size:12px;\'>收银员签字：<br />财务签字：</div>";
                strHtml += "<div style=\'padding-top:130px;\'>.</div>";

                myAddHtml(strHtml);
            }
            else {
                message('message.html?t=514', '300px', '200px');
            }
        }
    });
}

//交班清单
function shiftlist() {
    var number = $.cookie('sysnumber');
    $.ajax({
        url: url + 'shift/inventory',                                        //请求地址
        type: 'POST',                                                   //请求类型
        dataType: "json",                                               //返回值类型
        data: {
            "number": number                                        //参数
        },
        success: function (data) {
            if (data.code == 200 && typeof(data.data.goodsType) != "undefined") {
                var weChat = typeof(data.data.payType.weChat) != "undefined" ? data.data.payType.weChat : 0,
                    bankCard = typeof(data.data.payType.bankCard) != "undefined" ? data.data.payType.bankCard : 0,
                    payPal = typeof(data.data.payType.payPal) != "undefined" ? data.data.payType.payPal : 0,
                    memberCard = typeof(data.data.payType.memberCard) != "undefined" ? data.data.payType.memberCard : 0,
                    rmb = typeof(data.data.payType.rmb) != "undefined" ? data.data.payType.rmb : 0,
                    weRefundChat = typeof(data.data.payRefundType.weChat) != "undefined" ? data.data.payRefundType.weChat : 0,
                    bankRefundCard = typeof(data.data.payRefundType.bankCard) != "undefined" ? data.data.payRefundType.bankCard : 0,
                    payRefundPal = typeof(data.data.payRefundType.payPal) != "undefined" ? data.data.payRefundType.payPal : 0,
                    memberRefundCard = typeof(data.data.payRefundType.memberCard) != "undefined" ? data.data.payRefundType.memberCard : 0,
                    rmbRefund = typeof(data.data.payRefundType.rmb) != "undefined" ? data.data.payRefundType.rmb : 0,
                    recharge = typeof(data.data.rechargeMoney) != "undefined" ? data.data.rechargeMoney : 0,
                    orderAmount = weChat + bankCard + payPal + memberCard + rmb,
                    refundAmount = data.data.totalPrice,
                    turnAmount = orderAmount - refundAmount + recharge;
                $('#orderamount').html(orderAmount.toFixed(2));
                $('#totalorder').html(data.data.totalCount);
                $('#salesamount').html(turnAmount.toFixed(2));
                $('#returnamount').html(refundAmount);
                $('.shiftNumber').html('当班单号：' + data.data.userInfo.number);
                $('.shiftName').html('收银员：' + $.cookie('realName'));
                $('.shiftStartTime').html('开始时间：' + data.data.userInfo.startTime);
                $('.shiftEndTime').html('结束时间：' + data.data.userInfo.endTime);
                $.cookie('numberjb', data.data.payType.number);
                $('#wx').html((weChat - weRefundChat).toFixed(2));
                $('#ylk').html((bankCard - bankRefundCard).toFixed(2));
                $('#zfb').html((payPal - payRefundPal).toFixed(2));
                $('#hyje').html((memberCard - memberRefundCard).toFixed(2));
                $('#recharge').html(recharge.toFixed(2));
                $('#rmb').html((rmb - rmbRefund).toFixed(2));
                $('#yjje').html(turnAmount.toFixed(2));
                var json = eval(data.data.goodsType);
                for (var i = 0; i < json.length; i++) {
                    var name = json[i].name;
                    var counts = json[i].counts;
                    var amount = json[i].amount;
                    if (json.length - 1 == i) {
                        $("#jlice").prepend(' <tr><td class="transfer_bt">类别名称</td><td class="transfer_bt">销售数量</td><td class="transfer_bt">销售金额</td></tr>');
                    }
                    var a = 1;
                    a = a + i;
                    $("#jlice").prepend('<tr><td style="text-align: left">' + name + '</td><td>' + counts + '</td><td>' + amount + '</td></tr>');
                }
            }
            else {
                message('message.html?t=514', '300px', '200px');
            }
        }
    });
}

//交班确认
function shiftHandover(number) {
    $.ajax({
        url: url + 'shift',                                            //请求地址
        type: 'POST',                                                   //请求类型
        dataType: "json",                                               //返回值类型
        data: {
            "number": number                                        //参数
        },
        success: function (data) {
            if (data.code == 200 && data.data == "1") {
                $.cookie('realName', null);
                $.cookie('storeName', null);
                $.cookie('sysnumber', null);
                $.cookie('token', null);
                $.cookie('tradeNo', null);
                parent.top.window.location.replace('login.html');
            }
            else {
                message('message.html?t=515', '300px', '200px');
            }
        }
    });
}

function myAddHtml(strHtml) {
    var LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
    LODOP.PRINT_INIT("");
    LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", strHtml);
    LODOP.SET_PRINT_PAGESIZE(3, 600, 50, "");
    LODOP.PRINT();
    LODOP.PRINT_INIT("");
    LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", strHtml);
    LODOP.SET_PRINT_PAGESIZE(3, 600, 50, "");
    LODOP.PRINT();
}

//制保留2位小数，如：2，会在2后面补上00.即2.00  
function numFloat(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}

/*
 -----------------------------------------------------------------------------------
 全局量
 */

function addCookie(name, value, expireHours) {
    var cookieString = name + "=" + escape(value) + "; path=/";
    //判断是否设置过期时间
    if (expireHours > 0) {
        var date = new Date();
        date.setTime(date.getTime() + expireHours * 3600 * 1000);
        cookieString = cookieString + ";expires=" + date.toGMTString();
    }
    document.cookie = cookieString;
}

function getCookie(name) {
    var strcookie = document.cookie;
    var arrcookie = strcookie.split("; ");
    for (var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split("=");
        if (arr[0] == name) return unescape(arr[1]);
    }
    return null;
}

/*
 -----------------------------------------------------------------------------------
 数据同步
 */

var hasDailyDataSynced = getCookie('hasDailyDataSynced');
if (!hasDailyDataSynced) {
    syncDailyData(function () {
        addCookie('hasDailyDataSynced', 1, 24);
    });
}
// 日数据更新
function syncDailyData(callback) {
    syncPromise('init/member').then(function (respMember) {
        parent.layer.msg(!!respMember ? '初始化会员完成！' : '初始化会员失败！');
        if (!!respMember) {
            return syncPromise('init/category');
        } else {
            return $.Deferred().reject();
        }
    }).then(function (respCategory) {
        parent.layer.msg(!!respCategory ? '初始化商品分类完成！' : '初始化商品分类失败！');
        if (!!respCategory) {
            return syncPromise('init/goods');
        } else {
            return $.Deferred().reject();
        }
    }).then(function (respGoods) {
        parent.layer.msg(!!respGoods ? '初始化商品完成！' : '初始化商品失败！');
        if (!!respGoods && callback) {
            callback();
        }
    });
}

setInterval(syncRealTimeData, 5 * 60 * 1000);

// 实时数据更新
function syncRealTimeData(callback) {
    console.log(new Date())
    // 同步收款单
    syncPromise('syncAmount').then(function (resp) {
        if (!!resp) {
            // 同步购物单
            return syncPromise('sync');
        } else {
            return $.Deferred().reject();
        }
    }).then(function (resp) {
        if (!!resp) {
            // 同步退款单
            return syncPromise('shopping/refund/syncAmount');
        } else {
            return $.Deferred().reject();
        }
    }).then(function (resp) {
        if (!!resp) {
            // 同步退货单
            return syncPromise('shopping/refund/sync');
        } else {
            return $.Deferred().reject();
        }
    }).then(function (resp) {
        if (!!resp && callback) {
            callback();
        }
    });
}

function syncPromise(route) {
    var def = $.Deferred();
    $.ajax({
        url: url + route,
        type: 'GET',
        success: function (result) {
            if (result.code == 200) {
                def.resolve(true);
            } else {
                def.reject(false);
            }
        }
    });
    return def;
}